package easy;

import java.util.Stack;

public class Solution_1047 {

    public String removeDuplicates(String s) {
        char[] chars = s.toCharArray();
        Stack<Character> stack = new Stack<>();
        stack.add(chars[0]);
        for (int i = 1; i < chars.length; i++) {
            if (stack.empty() || stack.peek() != chars[i]) {
                stack.push(chars[i]);
            } else {
                stack.pop();
            }
        }
        StringBuilder buffer = new StringBuilder();
        for (char c : stack) {
            buffer.append(c);
        }
        return buffer.toString();
    }

    /*public String removeDuplicates(String s) {
        char[] chars = s.toCharArray();
        int preIndex = -1;
        for (int i = 0; i < chars.length; i++) {
            if (preIndex == -1) {
                preIndex = i;
            } else {
                if (chars[preIndex] == chars[i]) {
                    chars[preIndex] = ' ';
                    chars[i] = ' ';
                    while (preIndex >= 0) {
                        if (chars[preIndex] != ' ') {
                            break;
                        }
                        preIndex--;
                    }
                } else {
                    preIndex = i;
                }
            }
        }
        StringBuilder buffer = new StringBuilder();
        for (char c : chars) {
            if (c != ' ') {
                buffer.append(c);
            }
        }
        return buffer.toString();
    }*/

    public static void main(String[] args) {
        Solution_1047 model = new Solution_1047();
        System.out.println(model.removeDuplicates("abbaca"));
        System.out.println(model.removeDuplicates("fsdfsdasss"));
        System.out.println(model.removeDuplicates("a"));
    }
}
